﻿
using Nasty.Core.Log;
using Nasty.Core.SuperExtension;
using SqlSugar;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Nasty.QuartzModule
{
    public class QuartzHostedService : IHostedService
    {
        private readonly QuartzDynamicService _quartzDynamicService;
        private readonly SqlSugarClient _client;

        public QuartzHostedService(QuartzDynamicService quartzDynamicService, SqlSugarClient client)
        {
            _quartzDynamicService = quartzDynamicService;
            _client = client;
        }


        public Task StartAsync(CancellationToken cancellationToken)
        {
            // 查询是否存在 SysQuartzTask 表
            bool isExist = _client.DbMaintenance.GetTableInfoList()
                .Any(t => t.Name.Equals("SysQuartzTask", StringComparison.OrdinalIgnoreCase));

            if (!isExist) 
            {
                SuperConsole.WriteInfo("未初始化定时任务表");
                SerilogLogger.LogWarning("未初始化定时任务表");
                return Task.CompletedTask;
            }

            var tasks = _client.Queryable<QuartzTask.QuartzTask>().Where((t) => t.IsEnabled).ToList();
            foreach (var task in tasks) 
            {
                var jobType = Type.GetType(task.Class);
                if (jobType != null)
                {
                    var result = _quartzDynamicService.AddJobAsync(task, jobType).Result;
                }
            }

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
